/**
 * 配置面板的mixin 文件，
 *
 * 有特殊情况就覆写方法
 */
import { nextTick } from 'vue';
export default {
  emits: ['chartMouse'],
  data() {
    return {
      resizeTimer: null,
      chartMouseTimer: null,
    };
  },
  beforeUnmount() {
    this.clearChart && this.clearChart();
    window.CollectGarbage && window.CollectGarbage();
  },
  methods: {

    // 点击空白处传空值
    emitBlankVal() {
      let oDiv = document.querySelector(`#${this.chartId}`);
      if (!oDiv) {
        return;
      }
      oDiv.onclick = () => {
        if (this.isBlank) {
          const params = {
            name: '',
            value: '',
          };
          this.chartClick(params);
        }
        this.isBlank = true;
      };
      oDiv = null;
    },
    resizeChart() {
      // 延迟执行，不然有可能会获取到原来的宽高，图表不重新渲染
      clearTimeout(this.resizeTimer);
      this.resizeTimer = setTimeout(async() => {
        await this.getQuotaChartWAndQuotaChartH();
        nextTick(() => {
          this.chart && this.chart.resize && this.chart.resize();
        });
      }, 200);
    },
    getQuotaChartWAndQuotaChartH() {
      return new Promise(resolve => {
        setTimeout(async() => {
          const dom = document.getElementById(`chartMain${this.widgetInstanceId}`);
          const w = dom ? dom.offsetWidth : 0;
          const h = dom ? dom.offsetHeight : 0;
          if (w || h) {
            if (w !== this.quotaChartW || h !== this.quotaChartH) {
              this.quotaChartW = w;
              this.quotaChartH = h;
              await this.getQuotaChartWAndQuotaChartH();
              resolve(false);
            } else {
              resolve(true);
            }
          } else {
            resolve(true);
          }
        }, 200);
      });
    },
    clearChart() {
      if (this.chart) {
        // 销毁前移除点击事件
        this.chart.off('click');
        this.chart.off('dataZoom');
        this.chart.off('legendselectchanged');
        this.chart.off('mouseover');
        this.chart.off('mousemove');
        this.chart.off('mouseout');
        this.chart.dispose();
        this.chart = null;
      }

      // 空白处事件销毁
      const oDiv = document.querySelector(`#${this.chartId}`);
      if (oDiv) {
        oDiv.onclick = null;
      }
    },

    // 双轴折线，柱形图图例点击
    lineBarLegendSelectChanged(params) {
      const option = this.chart.getOption();
      const { yAxis, series } = option;
      const { selected } = params;

      // 判断y轴是否显示
      const yAxisShows = {};
      Object.entries(selected).map(([key]) => {
        const serie = series.find(n => n.name === String(key));
        const { yAxisIndex } = serie;
        const isShow = selected[key];
        const oldIsShow = yAxisShows[yAxisIndex];
        if (oldIsShow === undefined) {
          yAxisShows[yAxisIndex] = isShow;
        } else {
          yAxisShows[yAxisIndex] = oldIsShow || isShow;
        }
      });

      Object.entries(selected).map(([key]) => {
        const serie = series.find(n => n.name === String(key));
        const { yAxisIndex } = serie;
        const isShow = yAxisShows[yAxisIndex];
        yAxis[yAxisIndex].show = isShow;
      });
      this.chart.clear();
      this.chart.setOption(option);
    },

    chartMouseEvent() {
      this.chart.getZr().on('mouseover', params=>{
        this.chartMouseMove(params);
      });
      this.chart.getZr().on('mousemove', params=>{
        this.chartMouseMove(params);
      });
      this.chart.getZr().on('mouseout', params=>{
        this.$emit('chartMouse', false);
      });
    },
    chartMouseMove(params) {
      // 鼠标移入后就禁止实时数据
      this.$emit('chartMouse', true);
      if (this.chartMouseTimer) {
        clearTimeout(this.chartMouseTimer);
      }
      this.chartMouseTimer = setTimeout(()=>{
        this.$emit('chartMouse', false);
      }, this.config.config.property.debounceTime * 1000);
    },

    // 饼图点击图例的时候更新总计
    pieLegendSelectChanged(params) {
      this.isBlank = false;
      const option = this.chart.getOption() || {};
      const [seriesItem] = option.series;
      const allData = seriesItem?.data || [];
      const newSum = allData.reduce((p, c, i)=>{
        const curSeriesName = c.name;
        if (params?.selected[curSeriesName]) {
          return p + c.trueValue;
        }
        return p;
      }, 0);
      const { series = [] } = option;
      if (series.length > 1) {
        const [, currentSeries = {}] = series;
        const [sumData] = currentSeries.data;
        sumData.value = newSum;
        currentSeries.label.formatter = `{title|${newSum}}`;
        this.chart.setOption(option);
      }
    },
  },
};
